﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public delegate Task RequestDelegate(HttpContext httpContent);

    public interface IApplicationBuilder
    {
        /// <summary>
        /// 注册提供的中间件
        /// </summary>
        /// <param name="func"></param>
        /// <returns></returns>
        public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> func);

        /// <summary>
        /// 将注册的中间件构建成一个RequestDelegate对象
        /// </summary>
        /// <returns></returns>
        RequestDelegate Build();
    }

    public class ApplicationBuilder : IApplicationBuilder
    {
        List<Func<RequestDelegate, RequestDelegate>> _middlewares = new List<Func<RequestDelegate, RequestDelegate>>();

        public RequestDelegate Build()
        {
            _middlewares.Reverse();

            return httpContext =>
            {
                RequestDelegate next = async r => { await r.Response.WriteAsync("==>end"); };

                foreach (var middleware in _middlewares)
                {
                    next = middleware(next);
                }

                return next(httpContext);
            };

            //return httpContext =>
            //{
            //    RequestDelegate end = async r => { await r.Response.WriteAsync("==>end222"); };

            //    var request3 = _middlewares[2](end);
            //    var request2 = _middlewares[1](request3);
            //    var request = _middlewares[0](request2);

            //    //var rst = request(httpContext);

            //    return request(httpContext);
            //};



        }

        public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> func)
        {
            _middlewares.Add(func);
            return this;
        }
    }
}
